package services

import (
    "sync"
    "time"
    "volux/utils"
)

type PerformanceStats struct {
    IOPS        int64   `json:"iops"`
    Throughput  int64   `json:"throughput"`
    Latency     float64 `json:"latency"`
    QueueDepth  int     `json:"queue_depth"`
    ErrorCount  int64   `json:"error_count"`
    ActiveConns int     `json:"active_connections"`
}

type MonitorService struct {
    mu    sync.RWMutex
    stats map[string]*PerformanceStats // key: subsystem NQN
}

func NewMonitorService() *MonitorService {
    ms := &MonitorService{
        stats: make(map[string]*PerformanceStats),
    }
    go ms.collectStats()
    return ms
}

func (ms *MonitorService) collectStats() {
    ticker := time.NewTicker(time.Second * 100)
    for range ticker.C {
        spdkClient := utils.GetSPDKClient()
        if spdkClient == nil {
            continue
        }
        resp, err := spdkClient.Call("nvmf_get_stats", nil)
        if err != nil {
            continue
        }
        // 将 resp.Result 转换为 map[string]interface{}
        resultMap, ok := resp.Result.(map[string]interface{})
        if !ok {
            utils.LogError("failed to cast response result")
            continue
        }
        
        ms.mu.Lock()
        // 更新性能统计数据（假设 resultMap 中的其他字段为统计数据）
        for nqn, stat := range resultMap {
            // 排除 poll_groups 字段，假设 nqn 非 "poll_groups"
            if nqn == "poll_groups" {
                continue
            }
            s, ok := stat.(map[string]interface{})
            if !ok {
                continue
            }
            ms.stats[nqn] = &PerformanceStats{
                IOPS:        int64(s["iops"].(float64)),
                Throughput:  int64(s["bytes_per_second"].(float64)),
                Latency:     s["latency_us"].(float64),
                QueueDepth:  int(s["queue_depth"].(float64)),
                ErrorCount:  int64(s["error_count"].(float64)),
                ActiveConns: int(s["active_connections"].(float64)),
            }
        }
        ms.mu.Unlock()

        pollGroups, ok := resultMap["poll_groups"].([]interface{})
        if !ok {
            utils.LogError("failed to cast poll_groups to []interface{}")
            continue
        }
        for _, pg := range pollGroups {
            group, ok := pg.(map[string]interface{})
            if !ok {
                continue
            }
            // ...处理每个group的数据...
            _ = group // 占位，避免未使用错误
        }
    }
}

// GetSubsystemStats 获取指定子系统的性能统计
func (ms *MonitorService) GetSubsystemStats(nqn string) *PerformanceStats {
    ms.mu.RLock()
    defer ms.mu.RUnlock()
    return ms.stats[nqn]
}

// GetAllStats 获取所有子系统的性能统计
func (ms *MonitorService) GetAllStats() map[string]*PerformanceStats {
    ms.mu.RLock()
    defer ms.mu.RUnlock()
    return ms.stats
}